package com.myosw.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;

import org.myosw.solr.PageUtil;
import org.myosw.solr.SolrUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.myosw.cache.common.SearchlogEhCache;
import com.myosw.cache.common.VisitlogEhCache;
import com.myosw.dao.SearchlogDao;
import com.myosw.entity.SearchlogShow;
import com.myosw.pojo.Searchlog;
import com.myosw.util.Base64Coder;

public class SearchAction extends BaseAction
{

	private static Logger _log = LoggerFactory.getLogger(SearchAction.class);
		@Override
		public void execute() throws ServletException, IOException {
			
			
			String keyword= request.getParameter("keyword");
			int pagecount = request.getParameter("page")==null?1 :Integer.parseInt(request.getParameter("page"));
			int size = 10;
			PageUtil page = SolrUtils.query(keyword, pagecount, size );
			
			_setSearchlog(keyword);
			List<SearchlogShow> list = searchlogDao.getTop(0, 15);
			
			root.put("page", page);
			root.put("keyword", keyword);
			root.put("slist", list);
			printFreemarker("default/search.ftl", root);
		}
		
		
		public void link()
		{
			String url = request.getParams()[0];
			url =Base64Coder.decodeUrlBase64Safe(url);
			String title = request.getParameter("title");
			_setVisitlog(url,title);
			sendRedirect(url);
		}
		
		/**
		 * 自动填充
		 */
		public void auto()
		{
		String mask =request.getParameter("mask");
		_log.info("自动填充{}",mask);
		
		
		List<Searchlog> list = searchlogDao.getSearchlogs(mask);
			String xml = "<select>";
			for (Searchlog searchlog : list) {
				xml=xml+"<option >"+searchlog.getKeyword()+"</option>";
			}
			xml=xml+"</select>" ;
			printHtml(xml);
		}
		
		
		private void _setSearchlog(String keyword)
		{
			Object[] objects = new Object[2];
			objects[0] = keyword;
			objects[1]= new Timestamp(new Date().getTime());
			SearchlogEhCache.setlog(keyword+session.getId(), objects);
		}
		
		private void _setVisitlog(String url,String title)
		{
			Object[] objects = new Object[4];
			objects[0] = url;
			objects[1]= new Timestamp(new Date().getTime());
			objects[2]=title;
			objects[3] = request.getRemoteAddr();//取得ip
			VisitlogEhCache.setlog(url+session.getId(), objects);
		}
		
		SearchlogDao searchlogDao = new SearchlogDao();

}
